<?php
declare (strict_types=1);

namespace app\command;

use app\common\lib\File;
use app\service\SmsService;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\app;
use think\facade\Cache;
use app\common\lib\MsgQueue;
use app\common\lib\Redis;
use app\models\common\OauthClientsModel;
use app\models\common\OauthResourcesModel;
use app\models\common\OutApiAccessLogModel;
use app\repository\common\OauthClients;
use app\common\lib\Image;
use think\facade\Db;


class Test extends Command
{
    protected $output;

    protected function configure()
    {
        // 指令配置
        $this->setName('TEST')
            ->addOption('action', null, Option::VALUE_REQUIRED, '操作项')
            ->setDescription('测试脚本');
        $this->addArgument('args1', Argument::OPTIONAL, "参数1");
        $this->addArgument('args2', Argument::OPTIONAL, "参数2");
        $this->addArgument('args3', Argument::OPTIONAL, "参数3");
        $this->addArgument('args4', Argument::OPTIONAL, "参数4");
        $this->addArgument('args5', Argument::OPTIONAL, "参数5");
        $this->addArgument('args6', Argument::OPTIONAL, "参数6");
    }

    /**
     * Note:执行入口
     * User:端木凌风
     * Date:2022-11-22 17:49
     */
    protected function execute(Input $input, Output $output)
    {
        $this->output = $output;
        $action = $input->getOption('action') ?? 'help';
        $param = [
            'args1' => $input->getArgument('args1') ?? "",
            'args2' => $input->getArgument('args2') ?? "",
            'args3' => $input->getArgument('args3') ?? "",
            'args4' => $input->getArgument('args4') ?? "",
            'args5' => $input->getArgument('args5') ?? "",
            'args6' => $input->getArgument('args6') ?? "",
        ];
        $actions = $this->getAction();
        $act = $actions[$action]['action'] ?? 'help';
        return $this->$act($param);
    }

    private function getAction()
    {
        return [
            'TEST' => ['action' => 'test', 'des' => '测试'],
            'RPC' => ['action' => 'rpcTest', 'des' => 'RPC接口测试'],
            'RpcSms' => ['action' => 'rpcSendSms', 'des' => 'RPC接口发送短信'],
            'RpcFile' => ['action' => 'rpcUploadFile', 'des' => 'RPC接口上传文件'],
            'MsgQueue' => ['action' => 'messageQueue', 'des' => 'MQ普通消息测试'],
            'MsgQueueDelay' => ['action' => 'messageQueueDelay', 'des' => 'MQ延迟消息测试'],
        ];
    }


    private function test(array $params = [])
    {
        echo "\033[32mhello world!\033[0m\n";

    }

    /**
     * Note:RPC接口测试
     * User:端木凌风
     * Date:2022-11-28 13:55
     * @param array $params
     * @return void
     * @throws \Exception
     */
    private function rpcTest(array $params = [])
    {
        $uris = config('hprose.uris');
        $uri = $uris[0] ?? 'tcp://127.0.0.1:1314';
        $uri = str_replace('0.0.0.0', '127.0.0.1', $uri);
        $client = new \Hprose\Socket\Client($uri, false);
        $client->setTimeout(10000);
        $client->addFilter(new \app\service\RpcService\Helper\CompressFilter());
        $requestTime = date('Y-m-d H:i:s');
        $args = $this->createSign($requestTime);
        $data = [
            'header' => [
                'api_key' => $args['api_key'],
                'sign' => $args['sign'],
                'request_time' => $requestTime
            ],
            'body' => [
                'args1' => '参数1',
                'args2' => '参数2',
            ]
        ];

        $res = $client->test->Test(json_encode($data));
        dump(json_decode($res, true));
    }


    /**
     * Rpc接口上传文件
     * @return void
     */
    private function rpcUploadFile(array $params = [])
    {
        $uris = config('hprose.uris');
        $uri = $uris[0] ?? 'tcp://127.0.0.1:1314';
        $uri = str_replace('0.0.0.0', '127.0.0.1', $uri);

        $filePath = public_path() . '/static/manage/images/face.jpg';
        $newFilename = md5(time() . mt_rand(10, 1000)) . '.jpg';
        $fileMd5 = md5_file($filePath);
        $client = new \Hprose\Socket\Client($uri, false);
        $client->setTimeout(10000);
        $client->addFilter(new \app\service\RpcService\Helper\CompressFilter());

        $base64Data = base64_encode(file_get_contents($filePath));
        $requestTime = date('Y-m-d H:i:s');
        $args = $this->createSign($requestTime);

        $data = [
            'header' => [
                'api_key' => $args['api_key'],
                'sign' => $args['sign'],
                'request_time' => $requestTime
            ],
            'body' => [
                'path' => 'face',
                'block_sn' => 1,
                'block_total' => 1,
                'new_filename' => $newFilename,
                'type' => 2,
                'file' => $base64Data,
                'file_md5' => $fileMd5,
                'resize' => json_encode(['width' => 375, 'height' => 308, 'resize_type' => 2, 'left_original' => 1, 'bgcolor' => ''])
            ]
        ];
        $res = $client->files->uploadFile(json_encode($data));
        dump(json_decode($res, true));
    }

    private function rpcSendSms($params = [])
    {
        $client = new \Hprose\Socket\Client('tcp://127.0.0.1:9508', false);
        $client->setTimeout(10000);
        $client->addFilter(new \app\service\RpcService\Helper\CompressFilter());
        $requestTime = date('Y-m-d H:i:s');
        $args = $this->createSign($requestTime);
        $data = [
            'header' => [
                'api_key' => $args['api_key'],
                'sign' => $args['sign'],
                'request_time' => $requestTime
            ],
            'body' => [
                'mobile' => '17685908141',
                'content' => '您的验证码：' . mt_rand(1000, 9999),
                'sign_name' => '阿里云短信测试',
                'template_code' => 'SMS_154950909',
                'code' => mt_rand(1000, 9999)
            ]
        ];
        $res = $client->sms->single(json_encode($data));
        dump(json_decode($res, true));
    }

    /**
     * Note:MQ普通消息测试
     * User:端木凌风
     * Date:2022-01-20 11:24
     * @param $param
     * @return void
     */
    private function messageQueue($param = [])
    {
        $data = [
            'id' => 1,
            'sign' => 'normal',
            'sendTime' => date('Y-m-d H:i:s')
        ];
        $mq = new MsgQueue();
        $mq->sendMessage(MsgQueue::QUEUE_NORMAL, $data);
        echo date("Y-m-d H:i:s") . ":消息已发出\n";
    }

    /**
     * Note:MQ延迟消息测试
     * User:端木凌风
     * Date:2022-01-20 11:32
     * @param $params
     * @return void
     */
    private function messageQueueDelay($params = [])
    {
        $delay = mt_rand(10, 30);
        $data = [
            'id' => 1,
            'sign' => 'delay',
            'delaySecond' => $delay,
            'sendTime' => date('Y-m-d H:i:s')
        ];
        $mq = new MsgQueue();
        $mq->sendMessage(MsgQueue::QUEUE_DELAY_NORMAL, $data, true, $delay);
        echo date("Y-m-d H:i:s") . ":延迟消息已发出;延迟{$delay}秒\n";
    }

    private function createSign($requestTime)
    {
        $client = new OauthClientsModel();
        $list = $client->getRecordList(['personal_access_client' => 0, 'password_client' => 0], 0, 1);
        $info = $list[0];

        if (!$info) {
            dump("未配置凭证授予客户端");
            exit;
        }
        $apiKey = $info['id'];
        $apiSecret = $info['secret'];
        return [
            'api_key' => $info['id'],
            'sign' => md5("api_key=" . $apiKey . "&request_time=" . $requestTime . "&api_secret=" . $apiSecret)
        ];
    }

    private function help()
    {
        $actions = $this->getAction();
        $this->output->writeln("\033[33m操作项：\033[0m");
        foreach ($actions as $key => $val) {
            $key = str_pad($key, 30, ' ', STR_PAD_RIGHT);
            $this->output->writeln("\033[32m{$key}\033[0m\t{$val['des']}");
        }
    }


}
